<template>
  <VDialogContent
    @submit="submit"
    title="模板导入"
    @close="emit('close')"
    :loadidng="loading"
    :submitVisible="true"
  >
    <NScrollbar>
      <div class="content">
        <NForm
          ref="formRef"
          require-mark-placement="left"
          label-placement="left"
          :rules="rules"
          :label-width="120"
          :model="formModel"
          style="width: 800rem"
          label-align="right"
        >
          <NFormItem
            label="附件:"
            path="fileList"
            style="margin-left: -35rem"
          >
            <NUpload
              :max="1"
              :custom-request="commonUpload"
              @remove="commonRemove"
            >
              <NButton
                style="width: 115px; margin-bottom: 10rem; margin-left: 10rem"
                type="primary"
                ghost
              >
                上传文件
              </NButton>
            </NUpload>
          </NFormItem>
        </NForm>
      </div>
    </NScrollbar>
    <NModal
      :auto-focus="false"
      :mask-closable="false"
      v-model:show="processVisible"
    >
      <n-progress
        type="line"
        style="width: 200px"
        status="success"
        :percentage="percentage"
      >
        {{ percentage }}%
      </n-progress>
    </NModal>
  </VDialogContent>
</template>

<script setup lang="ts">
import {
  NScrollbar,
  cardProps,
  NUpload,
  useMessage,
  NForm,
  NButton,
  NFormItem,
  type FormRules,
  NModal,
  NProgress
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import { ref, reactive } from 'vue'
import type { UploadFileInfo, UploadCustomRequestOptions, FormInst } from 'naive-ui'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const props = defineProps({
  ...cardProps,
  value: {
    type: String
  },
  uid: {
    type: String
  }
})
const emit = defineEmits<{
  (event: 'close'): void
  (event: 'update'): void
  (event: 'error', msg: any): void
}>()
const message = useMessage()

const formModel = reactive({
  fileList: [] as UploadFileInfo[]
})

const rules: FormRules = {
  fileId: {
    required: true,
    message: '附件不能为空',
    trigger: ['input', 'change'],
    type: 'array'
  }
}

//文件上传
const commonUpload = async ({ file, onFinish, onError }: UploadCustomRequestOptions) => {
  try {
    formModel.fileList.push(file)
    onFinish()
  } catch (error) {
    onError()
  }
}
// 删除附件
async function commonRemove() {
  formModel.fileList = []
}

//确定
const formRef = ref<FormInst | null>(null)
const loading = ref(false)
const percentage = ref(0)
const processVisible = ref(false)
const timer = ref<number | null>(null)
async function submit() {
  formRef.value?.validate(async (err) => {
    if (err) return
    loading.value = true
    try {
      const formData = new FormData()
      formData.append('file', formModel.fileList[0].file!)
      formData.append('batchId', props?.uid!)
      processVisible.value = true
      const [error, res] = await sendRequest({
        module: 'batchV2',
        api: 'importCollectionItmes',
        override: {
          data: formData,
          onUploadProgress: (e) => {
            console.log(e.progress, e.loaded, e.total)
            const complete = Math.round((e.loaded * 100) / e.total)
            // percentage.value = Math.round((e.loaded * 100) / e.total)
            // 超过80 开始干涉
            if (complete >= 80) {
              if (timer.value) return
              timer.value = window.setInterval(() => {
                percentage.value += Math.round((100 - percentage.value) * 0.2) // 每次增加剩下的20%

                // 超过99 不再变化（此时也接近上传完成了）
                if (percentage.value > 99) {
                  timer.value && window.clearInterval(timer.value)
                }
              }, 1000)
            } else {
              // 在80之前都按照axios计算出的进度来显示
              percentage.value = complete
            }
          }
        }
      })
      if (error) return message.error(error.message)
      percentage.value = 100
      // 100加载完成再关闭进度条
      setTimeout(() => {
        console.log('结束')
      }, 500)
      emit('error', res.data)
      timer.value && window.clearInterval(timer.value)
      processVisible.value = false
      emit('update')
      emit('close')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.form_content {
  width: 100%;
  height: 100%;
  padding: 0 20rem 0rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
        }
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

.draggerBox {
  width: 280rem;
  height: 84rem;
  border-radius: 4rem;
  border: 1rem solid #3d90cc;
  background: transparent;
}

.uploadBox {
  display: flex;
}

:deep(.n-upload-trigger + .n-upload-file-list) {
  width: 530rem !important;
}
</style>
